package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Program: WebServerTomcat
 * @Author: Evan
 * @Date: 2022-05-16 11:10
 * @Description: 处理客户端请求
 * @Version: V1.0
 */
public class HttpServletRequest {
    private Socket socket;

    private String method;
    private String url;
    private String protocol;
    private Map<String, String> headers = new HashMap<>();
    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        parseRequestLine();
        parseHeaders();
        parseContent();
    }

    private void parseRequestLine() throws IOException {
        /*解析请求行*/
        String line = readLine();
        System.out.println("请求行:"+line);
        String[] data = line.split("\\s");

        method = data[0];
        url = data[1];
        protocol = data[2];
        System.out.println("method:"+method);
        System.out.println("url:"+url);
        System.out.println("protocol:"+protocol);
    }

    private void parseHeaders() throws IOException {
        while (true){
            String line = readLine();
            if (line.isEmpty()){
                break;
            }
            String[] data = line.split(":\\s");
            headers.put(data[0],data[1]);
            System.out.println(line);
        }
        System.out.println("headers:"+headers);
    }

    private void parseContent(){

    }

    public String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        int d;
        char cur = 'a';
        char pre = 'a';
        while ((d = in.read()) != -1){
            cur = (char) d;
            if (pre == 13 && cur ==10){
                break;
            }
            builder.append(cur);
            pre =cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }
}
